package it.koutifaris.travianmap.dal.sqlservices.mapuiservice;

import it.koutifaris.travianmap.dal.MapUIService;
import it.koutifaris.travianmap.dal.sqlservices.SqlMapUIContract.MapViewStates;
import it.koutifaris.travianmap.utils.cursor.ColumnNameCursorWrapper;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class SqlMapUIService implements MapUIService {

	private final SQLiteDatabase db;

	public SqlMapUIService(SQLiteDatabase db) {
		this.db = db;
	}

	@Override
	public MapViewState readState() {
		String[] columns = { MapViewStates.COLUMN_NAME_X, MapViewStates.COLUMN_NAME_Y, MapViewStates.COLUMN_NAME_ZOOM };
		Cursor cursor = db.query(MapViewStates.TABLE_NAME, columns, null, null, null, null, null);

		MapViewStateImpl result = getMapViewStateFromCursor(new ColumnNameCursorWrapper(cursor));
		cursor.close();

		return result;
	}

	private MapViewStateImpl getMapViewStateFromCursor(ColumnNameCursorWrapper cursor) {
		MapViewStateImpl result;

		if (cursor.moveToNext()) {
			int x = cursor.getInt(MapViewStates.COLUMN_NAME_X);
			int y = cursor.getInt(MapViewStates.COLUMN_NAME_Y);
			float zoom = cursor.getFloat(MapViewStates.COLUMN_NAME_ZOOM);

			result = new MapViewStateImpl(x, y, zoom);
		} else {
			result = MapViewStateImpl.initialState();
		}

		return result;
	}

	@Override
	public void writeState(MapViewState viewState) {
		db.insertWithOnConflict(MapViewStates.TABLE_NAME, null, getContentValues(viewState), SQLiteDatabase.CONFLICT_REPLACE);
	}

	private ContentValues getContentValues(MapViewState viewState) {
		ContentValues values = new ContentValues();
		values.put(MapViewStates.PK_ID, 1);
		values.put(MapViewStates.COLUMN_NAME_X, viewState.getX());
		values.put(MapViewStates.COLUMN_NAME_Y, viewState.getY());
		values.put(MapViewStates.COLUMN_NAME_ZOOM, viewState.getZoom());

		return values;
	}

	@Override
	public void close() {
		db.close();
	}

}
